<template>
    <div>
    <Modal
        v-model="modal.show"
        :title="modal.title"
        :loading="modal.loading"
        @on-ok="saveContent"
        @on-cancel="hideModal"
        :width="800"
    >
        <Form ref="formValidate" :model="formValidate" :label-width="80" :rules="ruleValidate">
            <FormItem label="名称" prop="templName">
                <Input
                    v-model="formValidate.templName"
                    :maxlength="64"
                    :placeholder="nameErrorTip"
                ></Input>
            </FormItem>
            <FormItem label="类型" prop="typeId">
                <Select filterable v-model="formValidate.typeId" placeholder="类型" filterable>
                    <Option v-for="(value, key) in typeRecordData" :value="value.id" :key="key">{{
                        value.typeName
                    }}</Option>
                </Select>
            </FormItem>
            <FormItem label="选择模板" prop="templ">
                <div class="flex">
                    <FormItem v-if="op == 'add'">
                        <Upload
                            :format="['json', 'JSON']"
                            action="/api/virtual/template/add"
                            :before-upload="handleUpload"
                            :show-upload-list="false"
                            style="display: inline-block"
                        >
                            <Button icon="ios-cloud-upload-outline">上传</Button>
                        </Upload>
                        <WarningTip content="请上传json格式文件或选择模板"></WarningTip>
                    </FormItem>
                    <FormItem style="margin-left: 4px; flex: auto">
                        <Select filterable
                            v-model="formValidate.templId"
                            placeholder="模板"
                            @on-change="changeTempl"
                            filterable
                            clearable
                        >
                            <Option
                                v-for="(value, key) in templateList"
                                :value="value.id"
                                :key="key"
                                >{{ value.name }}</Option
                            >
                        </Select>
                    </FormItem>
                </div>
                <div class="fileStyle" v-if="fileName">文件名称: {{ fileName }}</div>
                <img v-if="currentPicUrl" v-show="!loadError" :src="currentPicUrl" @error="hideImg" style="maxWidth:100%;" @click="showPic"/>
            </FormItem>
            <FormItem label="描述">
                <!-- <Input
                    type="textarea"
                    :maxlength="200"
                    v-model="formValidate.description"
                    placeholder="最大长度为200个字符"
                ></Input> -->
                <quillEditor 
                    ref="myQuillEditor" 
                    :dataValue="formValidate.description" 
                    @editorChange="onEditorChange">
                </quillEditor>
            </FormItem>
        </Form>
    </Modal>
    <ImgView ref="imgView"></ImgView>
    <!-- <Modal v-model="picModal" width="1000">
        <img v-if="currentPicUrl" :src="currentPicUrl" style="maxWidth:100%;"/>
    </Modal> -->
    </div>
</template>
<script>
import { addTemplRelation, updateTemplRelation } from '../api/templRelation.js';
import { mapState } from 'vuex';
import { validateName1, nameErrorTip } from '@/libs/reg';
import { getTemplateData } from '@/api/proTemplate.js';
import { typeRecordMixin } from '../mixin/research';
import quillEditor from '@/components/quillEditor'
import ImgView from '@/components/common/img-view';
export default {
    name: 'EditModal',
    components: {ImgView,quillEditor},
    mixins: [typeRecordMixin],
    // inject: ['parent'],
    props: {
        title: {
            type: String,
            default: '',
        },
    },
    data() {
        const validateTempl = (value, rule, callback) => {
            //验证警戒值
            if (this.formValidate.templ) {
                callback();
            } else {
                callback(this.op === 'add' ? '请上传文件或选择模板' : '请选择模板');
            }
        };
        return {
            picModal:false,
            nameErrorTip,
            op: '',
            modal: {
                show: false,
                data: '',
                loading: true,
            },
            fileName: '',
            formValidate: {
                description: '',
                fileData: '',
                templ: '',
                templId: '',
                templName: '',
                typeId: '',
            },
            ruleValidate: {
                templName: [
                    { required: true, message: '请输入模板名称', trigger: 'blur' },
                    { validator: validateName1, trigger: 'change, blur' },
                ],
                typeId: [{ required: true, message: '请选择类型', trigger: 'change' }],
                templ: [{ required: true, validator: validateTempl, trigger: 'change' }],
            },
            templateList: [],
            loadError:false
        };
    },
    computed: {
        ...mapState('user', ['nickname', 'userId', 'isRootDesigner']),
        currentPicUrl(){
            this.loadError = false;
            let template = this.templateList.find(item => item.id === this.formValidate.templId)
            return template ? `/files${template.picUrl}` : ''
        }
    },
    watch: {
        'formValidate.templ': function (val, oldval) {
            (val || oldval) && this.$refs.formValidate.validateField('templ');
        },
    },
    mounted() {
        this.queryTypeRecordAll();
        this._formValidate = { ...this.formValidate };
    },
    methods: {
        hideImg(){
            console.log(this.currentPicUrl,'topo图片加载失败');
            this.loadError = true;
        },
        showModal(data) {
            let name = this.title;
            this.modal.show = true;
            this.op = data ? 'update' : 'add';
            this.getProtemList();
            if (!data) {
                this.modal.title = `创建${name}`;
                this.resetField();
            } else {
                this.modal.title = `修改${name}`;
                this.formValidate = {
                    ...data,
                    templ: data.templId,
                };
                this.fileName = '';
            }
        },
        resetField() {
            this.formValidate = { ...this._formValidate };
            this.fileName = '';
            this.$refs.formValidate.resetFields();
        },
        saveContent() {
            this.$refs.formValidate.validate((valid) => {
                if (valid) {
                    let params = { ...this.formValidate };
                    let reqApi;
                    if (this.op == 'add') {
                        reqApi = addTemplRelation(params);
                    } else {
                        reqApi = updateTemplRelation(params.id, params);
                    }
                    reqApi
                        .then(({ code, message }) => {
                            if (code === 1) {
                                this.$Message.info(`${this.modal.title}成功`);
                                this.hideModal();
                                this.$emit('ok', this.op);
                            } else {
                                this.$Message.error(message);
                            }
                            this.cancelLoading();
                        })
                        .catch((error) => {
                            this.cancelLoading();
                        });
                } else {
                    this.cancelLoading();
                }
            });
        },
        handleUpload(file) {
            let _this = this;
            let nameArr = file.name.split('.');
            let fileType = nameArr[nameArr.length - 1];
            if (fileType !== 'json' && fileType !== 'JSON') {
                _this.$Message.error({
                    content: '请选择json文件',
                    duration: 5,
                });
                return false;
            }
            this.fileName = file.name;
            const reader = new FileReader();
            reader.readAsText(file, 'UTF-8');
            reader.onload = function (evt) {
                let newjson = evt.target.result;
                _this.formValidate.fileData = newjson;
                _this.notNeedTriggerChange = true;
                _this.formValidate.templId = '';
                _this.formValidate.templ = newjson;
                // this.result为读取到的json字符串，需转成json对象
                // 检测是否导入成功
            };
            return false;
        },
        changeTempl(id) {
            if (this.notNeedTriggerChange) {
                this.notNeedTriggerChange = false;
                return;
            }
            this.formValidate.templ = id;
            this.fileName = '';
            this.formValidate.fileData = '';
        },
        hideModal() {
            this.modal.show = false;
            this.resetField();
        },
        cancelLoading() {
            this.modal.loading = false;
            setTimeout(() => {
                this.modal.loading = true;
            });
        },
        getProtemList() {
            let query = {
                pageIndex: 1,
                pageSize: 10000,
            };
            let params = {
                type: 'project',
                // rangeId: this.rangeId
            };
            getTemplateData(params, query).then(({data:{ code, data, message } }) => {
                if (code === 1) {
                    this.templateList = data.items;
                } else {
                    this.templateList = [];
                }
            });
        },
        showPic(e){
            this.$refs.imgView.showModal(e.target);
        },
        onEditorChange(val){
            this.formValidate.description = val;
        }
    },
};
</script>
<style scoped></style>
